import { InfiniteScroll, Input, Mask, Modal, Toast } from 'antd-mobile'
import React, { useLayoutEffect, useRef, useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { getValentineList, joinRoom, getValentineNoticeList, buyTicket, openBox, getValentinRecord, NoticeList } from '../../../api/active'
import { GetUserInfo } from '../../../api/mine'
import './index.less'
import { compareVersions, getVersion } from '../../../utils/util'
import appSdk from '../../../utils/app_sdk'

const typeKey = {
  粉玫瑰: 1,
  红玫瑰: 2
} // 用这个判断

let intervalId = null
let totalNum = {}
const env = process.env.REACT_APP_ENV

const wsUrl = {
  test: 'ws://119.91.142.209:8282'
  // 'dev': "ws://119.91.142.209:8282",
  // 'release': "wss://ws.aimengtec.com:8282",
  // 'prd': "wss://ws.aimengtec.com:8282",
}

export default function ValentineLottery() {
  const navigate = useNavigate()
  const ws = useRef('')
  // const [message, setMessage] = useState('');
  const [isConnected, setIsConnected] = useState(false)
  const [buyNum, setBuyNum] = useState(1)
  const [prizePool, setPrizePool] = useState({ total: 0, num: 0 }) // 奖池

  const [noMoneyVisible, setNoMoneyVisible] = useState(false)
  const [buyModalVisible, setBuyModalVisible] = useState(false)
  const [isNoMoney, setIsNoMoney] = useState(false) // 没米钻 是true

  const [recordVisibale, setRecordVisibale] = useState(false)
  const [hasSpecial, setHasSpecial] = useState(false) // 是否有大奖

  const [noticeList, setNoticeList] = useState([])
  const [moData, setMoData] = useState([])

  const [poolRate, setPoolRate] = useState({})
  // ws://119.91.142.209:8282
  useLayoutEffect(() => {
    console.log('重连了吗', ws.current)
    ws.current = new WebSocket(wsUrl[env])
    ws.current.onopen = (e) => {
      console.log('链接成功')
      setIsConnected(true)
    }
    ws.current.onmessage = (e) => {
      // e.data readyState 1 成功
      if (e.data) {
        const data = JSON.parse(e.data)
        if (+data.opCode === 101) {
          joinRoom({
            room_id: '101',
            client_id: data.data
          }).then((res) => {
            console.log(res)
          })
        }
        if (+data.opCode === 108) {
          // 抽奖
          // data.data.num data.data.id
          // updateData(false)
          console.log(poolRate)
          setPoolRate({
            ...poolRate,
            [data.data.id]: 1 - Number(data.data.num) / Number(totalNum[data.data.id])
          })
          console.log('奖池', data.data.id, '剩余', 1 - Number(data.data.num) / Number(totalNum[data.data.id]))
        }
        if (+data.opCode === 109 && data.data) {
          // 抽奖
          setNoticeList(noticeList.concat([data.data]))
        }
        console.log('ws', e.data, ws)
      }
      // setMessage(e)
    }
    ws.current.onclose = () => {
      setIsConnected(false)
    }
    ws.current.onerror = (err) => {
      console.log('ws error', err)
      // Toast.show({
      // 	content: '连接奖池失败, 请刷新重试'
      // })
    }
    return () => {
      setIsConnected(false)
      ws.current?.close()
    }
  }, [ws])

  // 心跳
  useEffect(() => {
    if (isConnected && ws.current) {
      intervalId = setInterval(() => {
        ws.current.send('Ping')
      }, 20000)
    }
    return () => {
      intervalId && clearInterval(intervalId)
    }
  }, [isConnected, ws])

  const [giftData, setGiftData] = useState([])
  const [tickInfo, setTickInfo] = useState({ ticket_id: 0, ticket_name: '', ticket_mizuan: 0, ticket_num: 0, ticket_img: '', id: 0 })
  const [xiQueNum, setXiQueNum] = useState(0)
  const [userinfo, setUserinfo] = useState() // mizuan mibi
  useEffect(() => {
    if (compareVersions(getVersion() || '1.0.0', '2.2.0') !== -1) {
      appSdk('setFullScreen', 1)
    }
    getNoticeList()
    // pot_count_nums : 10000
    // pot_residue_nums : 9952
    getValentineList().then((res) => {
      console.log(res.data.list)
      if (res.data && res.data.list.length) {
        setMoData(res.data.list)
        totalNum = {
          [res.data.list[0]?.id]: res.data.list[0]?.pot_count_nums,
          [res.data.list[1]?.id]: res.data.list[1]?.pot_count_nums
        }
        const { box_show_data } = res.data.list[0]
        // 多截 少补
        const arr =
          box_show_data.length <= 16
            ? box_show_data.concat(new Array(16 - box_show_data.length).fill({ img: '' }))
            : box_show_data.slice(0, 15)
        arr.splice(5, 0, {})
        arr.splice(6, 0, {})
        arr.splice(9, 0, {})
        arr.splice(10, 0, {})
        setGiftData(arr)
        setTickInfo(res.data.list[0])
        setXiQueNum(res.data.xique_num || 0)
        setPrizePool({
          total: +res.data.list[0].pot_count_nums,
          num: +res.data.list[0].pot_residue_nums
        })
        setPoolRate({
          [res.data.list[0].id]: 1 - +res.data.list[0]?.pot_residue_nums / +res.data.list[0]?.pot_count_nums,
          [res.data.list[1].id]: 1 - +res.data.list[1]?.pot_residue_nums / +res.data.list[1]?.pot_count_nums
        })
        // setImgList(res.data.list.map(() => ({
        // 	hyaline_img:
        // })))
      }
    })
    GetUserInfo().then((res) => {
      console.log('userinfo', res)
      setUserinfo(res.data)
    })
    getRecordList()
  }, [])

  const getNoticeList = () => {
    getValentineNoticeList().then((res) => {
      console.log(res)
      if (res.data) {
        setNoticeList(res?.data.concat(res?.data) || [])
      }
    })
  }

  const [rewardVisible, setRewardVisible] = useState(false)
  const [rewardData, setRewardData] = useState({ price_count_nums: 0, reward_data: [], special_awards_arr: {} })
  // 购买玫瑰
  const buyTicketFun = () => {
    if (+userinfo.mizuan >= +tickInfo.ticket_mizuan * +buyNum) {
      buyTicket({
        ticket_id: tickInfo.ticket_id,
        nums: buyNum
      }).then((res) => {
        setBuyModalVisible(false)
        setBuyNum(1)
        updateData()
        // if (res.data) {
        // 	setRewardData*
        // }
        Toast.show({
          content: '购买成功',
          icon: 'success'
        })
      })
    } else {
      console.log('钱不够了')
      setBuyModalVisible(false)
      setIsNoMoney(true)
      setNoMoneyVisible(true)
    }
  }

  // 开奖
  const getReward = (num) => {
    // 开奖 计算剩余ticket_num数量够不够
    if (+tickInfo?.ticket_num >= num) {
      Toast.show({
        content: '开奖中..',
        icon: 'loading',
        maskClickable: false
      })
      openBox({
        box_id: tickInfo.id,
        nums: num
      }).then((res) => {
        Toast.clear()
        console.log('购买成功，开出来', res, '有大奖吗', res.data.special_awards_arr)
        if (res.data) {
          setRewardVisible(true)
          if (res.data.reward_data && res.data.reward_data?.length) {
            setRewardData(res.data)
          }
        }
        console.log(res)
        updateData()
      })
    } else {
      console.log('当前余额', tickInfo?.ticket_num, '准备抽', num)
      setNoMoneyVisible(true)
    }
  }

  // 同步数据触发的
  const updateData = (more = true) => {
    if (more) {
      GetUserInfo().then((res) => {
        console.log('userinfo', res)
        setUserinfo(res.data)
      })
      getRecordList()
    }
    getValentineList().then((res) => {
      // console.log(res);
      // 找到当前所选的 保持不变
      setMoData(res.data.list)
      const item = res.data.list.find((item) => item.id === tickInfo.id)
      console.log('当前正用的奖池', item, tickInfo, res.data.list)
      if (item) {
        setTickInfo(item)
        setXiQueNum(res.data.xique_num || 0)
        setPrizePool({
          total: +item.pot_count_nums,
          num: +item.pot_residue_nums
        })
        setPoolRate({
          ...poolRate,
          [item.id]: 1 - Number(item.pot_residue_nums) / Number(totalNum[item.id])
        })
      }
    })
    getNoticeList()
  }

  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [recordList, setRecordList] = useState([])
  const getRecordList = async () => {
    try {
      const res = await getValentinRecord({ page })
      if (res.data && res.data?.length) {
        setRecordList(page === 1 ? res.data : recordList.concat(res.data))
      }
      if (res.data && res.data?.length >= 10) {
        setPage(page + 1)
        setHasMore(true)
      } else {
        setHasMore(false)
      }
    } catch {
      setHasMore(false)
    }
  }

  useEffect(() => {
    if (recordVisibale) {
      setPage(1)
      setHasMore(true)
      setRecordList([])
    }
  }, [recordVisibale])

  const [specialMask, setSpecialMask] = useState(false)
  // 关闭奖励
  const afterRewardClose = () => {
    // 表示有大奖
    if (rewardData.special_awards_arr && rewardData.special_awards_arr?.name && !hasSpecial) {
      setHasSpecial(true)
      setRewardData({
        ...rewardData,
        reward_data: [] // 普通 情况
      })
      setTimeout(() => {
        setSpecialMask(true) // 延迟打开
      }, 800)
    }
    // hasSpecial 表示关闭的是大奖弹窗
    if (hasSpecial) {
      setHasSpecial(false)
    }
    setRewardVisible(false)
  }

  const openSpecial = () => {
    setSpecialMask(false)
    setRewardVisible(true)
  }

  const loveProgress = () => {
    // if (!prizePool?.total || !prizePool?.num) return 0;
    const num = Math.floor(poolRate[tickInfo?.id] * 10000) / 100 || 0
    if (num <= 3) return 0
    if (num <= 15) return 10
    if (num <= 25) return 20
    if (num <= 35) return 30
    if (num <= 45) return 40
    if (num <= 55) return 50
    if (num <= 65) return 60
    if (num <= 75) return 70
    if (num <= 85) return 80
    if (num <= 99.999) return 90
    if (num === 100) return 0
  }

  return (
    <div className="active_bg ">
      <div className="back_icon" onClick={() => appSdk('backPress')}></div>
      <div className="active_content ">
        <div className="record_btn ">
          <div className="blur_bg "></div>
          <div className="text" onClick={() => setRecordVisibale(true)}>
            抽奖记录
          </div>
        </div>
        <div className="gonggao flex_center">
          <div className="con flex_center">
            <div className="icon"></div>
            <div className="txt_list">
              {noticeList.length > 0
                ? noticeList.map((item, idx) => (
                    <div key={String(idx)} className="txt">
                      恭喜 <span>{item.nickname}</span> 抽到 <span>{item.award}</span>
                    </div>
                  ))
                : null}
            </div>
            <div className="icon"></div>
          </div>
        </div>
        <div className="xi_que_info flex_center">
          <div>我的喜鹊：</div>
          <div>{xiQueNum}</div>
          <div className="icon"></div>
          <div onClick={() => navigate('/valentine/product')}>去兑换</div>
        </div>
        <div className="tag_wrap" style={{ marginTop: 16 }}>
          {moData.map((item) => (
            <div
              key={item.id}
              className={`item ${item.id === tickInfo.id ? 'active' : ''}`}
              onClick={() => {
                console.log(poolRate)
                setTickInfo(item)
                setPrizePool({
                  total: +item.pot_count_nums,
                  num: +item.pot_residue_nums
                })
                const { box_show_data } = item
                const arr =
                  box_show_data.length <= 16
                    ? box_show_data.concat(new Array(16 - box_show_data.length).fill({ img: '' }))
                    : box_show_data.slice(0, 15)
                arr.splice(5, 0, {})
                arr.splice(6, 0, {})
                arr.splice(9, 0, {})
                arr.splice(10, 0, {})
                setGiftData(arr)
              }}
            >
              <img src={item.id === tickInfo.id ? item?.img : item?.hyaline_img} alt="" />
            </div>
          ))}
        </div>
        {/* 奖品列表 */}
        {/* 6,7 10 11隐藏 */}
        <div className="reward_content">
          <div className="reward_list">
            {giftData.map((item, idx) => (
              <div className={`reward_box ${[5, 6, 9, 10].includes(idx) ? 'hidden' : ''}`} key={idx}>
                {item?.show_img ? <img src={item?.show_img} alt="" /> : null}
                {item?.num && item?.num > 1 ? <div className="num">x{item.num}</div> : null}
              </div>
            ))}
          </div>
          <div className="schedule_info">
            <div className="tit">
              <div className="txt"></div>
              <div className="icon"></div>
            </div>
            <div className={`love_point a_${loveProgress()}`}></div>
            <div className="point">
              <div className="num">{poolRate[tickInfo?.id] < 1 ? Math.floor(poolRate[tickInfo?.id] * 10000) / 100 : 0}%</div>
              {/* <div className="num a_1"></div> */}
              <div className="unit"></div>
            </div>
          </div>
        </div>
        <div className="xi_que_info flex_center">
          <div>我的{tickInfo?.ticket_name}：</div>
          <div>{tickInfo?.ticket_num}</div>
          <div className="icon">
            <img src={tickInfo.ticket_img} alt="" />
          </div>
          <div onClick={() => setBuyModalVisible(true)}>去购买</div>
        </div>
        <div className={`buy_groups type_${typeKey[tickInfo?.ticket_name]}`}>
          <div className="btn once" onClick={() => getReward(1)}></div>
          <div className="btn oncex10" onClick={() => getReward(10)}></div>
          <div className="btn oncex100" onClick={() => getReward(100)}></div>
        </div>
        <div className="rule">
          <div className="t">规则及概率说明</div>
          <div className="c">
            参与本次活动前，请您详细阅读活动规则及相关条款。凡参与本次活动，则视为您已阅读、理解并同意活动规则及注意事项全部内容。
          </div>
          <div>
            <p>抽奖奖励</p>
            <p>1、  本次活动分为两个奖池，抽奖券不通用。每次抽奖需要消耗1张抽奖券，每次抽奖必能获得对应奖池内道具。</p>
            <p>2、  抽奖池累计进度两个奖池不互通，当抽奖池进度满时，该用户会获得一个额外大奖，大奖不包含在奖池内，无法通过抽奖获取。</p>
            <p>3、  当抽奖池进度已充满，抽奖池进度将会重置</p>
            <p>喜鹊及奖励兑换</p>
            <p>1、  “喜鹊”为本次七夕抽奖活动的特殊产物，可在兑换商店中兑换奖励</p>
            <p>2、  本次活动结束后，会删除本次七夕活动所有参与用户的“喜鹊“，不再可使用</p>
            <p>活动说明</p>
            <p>1、利用漏洞或者是其他非法途径参与本活动，官方有权取消其活动参与资格。</p>
            <p>2、{window.baseConfig.package_name}有权清除活动中的非法数据。</p>
            <p>3、活动如有任何疑问请联系{window.baseConfig.package_name}客服。</p>
            <p>
              4、活动获得的所有虚拟道具及权益均不可进行转让、交易或变现，{window.baseConfig.package_name}官方有权对任何违规行为进行处理。
            </p>
            <p>*在此活动中，APPLE不是赞助者，也没有以任何形式参与活动</p>
          </div>
          <div className="rule_img">
            <img src={tickInfo?.rule_img} alt="" />
          </div>
        </div>

        {/* 余额不足提示弹窗 */}
        <Modal
          className={`no_monay_modal a_${typeKey[tickInfo?.ticket_name]} ${isNoMoney ? 'money' : ''}`}
          onClose={() => setNoMoneyVisible(false)}
          visible={noMoneyVisible}
          closeOnMaskClick={false}
          content={
            <div className="">
              <div className="no_more"></div>
              <div className="btn_group">
                <div className="cancel" onClick={() => setNoMoneyVisible(false)}></div>
                <div
                  className="buy"
                  onClick={() => {
                    if (isNoMoney) {
                      navigate('/recharge')
                    }
                    setNoMoneyVisible(false)
                    setBuyModalVisible(true)
                  }}
                ></div>
              </div>
            </div>
          }
        ></Modal>
        {/* 玫瑰购买 */}
        <Modal
          className="buy_modal"
          onClose={() => setBuyModalVisible(false)}
          visible={buyModalVisible}
          closeOnMaskClick={false}
          content={
            <div className="">
              <div className="tit_txt"></div>
              <div className="box_img">
                <img src={tickInfo.ticket_img} alt="" />
              </div>
              <div className="input_content">
                <div className="down bt" onClick={() => setBuyNum(buyNum > 1 ? +buyNum - 1 : 1)}></div>
                <div className="input">
                  <Input
                    onChange={(v) => {
                      if (v >= 9999) {
                        setBuyNum(9999)
                      } else {
                        setBuyNum(Number(v).toFixed(0).replace(/^0+/, ''))
                      }
                    }}
                    value={buyNum}
                    type="number"
                    min={1}
                    max={9999}
                  ></Input>
                </div>
                <div className="add bt" onClick={() => setBuyNum(buyNum < 9999 ? +buyNum + 1 : 9999)}></div>
              </div>
              <div className="money">
                需要{Number(buyNum) * Number(tickInfo.ticket_mizuan)}
                {window.baseConfig.coin_name}
              </div>
              <div className="btn_group">
                <div className="cancel" onClick={() => setBuyModalVisible(false)}></div>
                <div className="buy" onClick={buyTicketFun}></div>
              </div>
            </div>
          }
        ></Modal>
        {/* 开奖 */}
        <Modal
          visible={rewardVisible}
          onClose={afterRewardClose}
          className={`gift_modal ${hasSpecial ? 'special_reward' : ''} ${rewardData.reward_data?.length >= 3 && !hasSpecial ? 'long_wrap' : ''}`}
          closeOnMaskClick={true}
          destroyOnClose={true}
          content={
            <div className="gift_data">
              <div className="gift_box_img"></div>
              <div className="box_tit"></div>
              <div className="price">
                价值：{hasSpecial ? rewardData?.special_awards_arr?.price : rewardData?.price_count_nums}
                {window.baseConfig.coin_name}
              </div>
              {/* ${rewardData.reward_data?.length} */}
              <div className={`gift_list item_${hasSpecial ? 1 : rewardData.reward_data?.length}`}>
                {(hasSpecial ? [rewardData.special_awards_arr] : rewardData.reward_data)?.map((item) => (
                  <div className="item" key={item.id}>
                    {+item.nums > 1 ? <div className="nums">x{item.nums}</div> : null}
                    <img src={item.img} alt="" />
                    <div className="name ellipsis1">{item.name}</div>
                    <div className="item_price">{+item.price ? `${item.price}${window.baseConfig.coin_name}` : ''}</div>
                  </div>
                ))}
              </div>
            </div>
          }
        ></Modal>

        {/* 记录 */}
        <Modal
          closeOnMaskClick={true}
          onClose={() => setRecordVisibale(false)}
          visible={recordVisibale}
          className="record_modal"
          destroyOnClose
          content={
            <div>
              <RecordDetail recordList={recordList} getRecordList={getRecordList} hasMore={hasMore} />
            </div>
          }
        />

        {/* 大奖mask */}
        <Mask visible={specialMask} opacity={0.85}>
          <div className="special_reward">
            <div className="txt"></div>
            <div className="img animate__tada animate__animated"></div>
            <div className="btn" onClick={openSpecial}></div>
          </div>
        </Mask>
      </div>
    </div>
  )
}

export function RecordDetail({ recordList = [], getRecordList, hasMore }) {
  const [moreNote, setMoreNote] = useState('')
  return (
    <div className="record">
      <div className="tit">抽奖记录</div>
      <div className="list">
        {recordList.map((item) => (
          <div className="item_data" key={item.create_time}>
            <div
              className="item"
              onClick={() => {
                if (item.create_time === moreNote) {
                  setMoreNote(null)
                } else {
                  setMoreNote(item.create_time)
                }
              }}
            >
              <div className="info">
                <div className="name">
                  {item.box_name}x{item.nums}
                </div>
                <div className="time">{new Date(parseInt(item.create_time) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ')}</div>
              </div>
              <div className="note ellipsis1">{item.note}</div>
            </div>
            {moreNote === item.create_time ? <div className="more_note">{item.note}</div> : null}
          </div>
        ))}
        <InfiniteScroll loadMore={getRecordList} threshold={150} hasMore={hasMore} />
      </div>
    </div>
  )
}
